<template>
  <section class='f-meal'>
    <section class="f-top-box">
      <van-nav-bar class="f-nav-bar" title="国际套餐">
        <template #left>
          <van-icon v-if="isBack" name="arrow-left" size="18" @click="pageBack" />

          <div v-else class="f-nav-left" @click="changeMealType(1)">
            <img src="@/assets/icons/home_icon_china.png" alt="">
            <span>国内套餐</span>
          </div>
        </template>
      </van-nav-bar>

      <section class="f-header">
        <p>用户码</p>
        <div class="f-code">
          <van-field class="f-input" v-model="code" placeholder="请输入用户码" clearable type="number" @blur="setCode" />
          <img src="@/assets/icons/btn_arrow_white.png" alt="" @click="openPopupCode()">
        </div>
      </section>

      <section class="f-search">
        <section class="f-search-box" @click="toSearch">
          <img src="@/assets/icons/package_icon_search.png" alt="">
          <p>开始搜索</p>
        </section>

        <ul class="f-continent-box">
          <li v-for="(item,index) in continentList" :key="index"
            :class="{'f-continent-active': searchForm.continentCode == item.continentCode}" @click="handleContinent(item)">
            <img :src="continentImg[item.continentCode]" alt="">
            <p>{{ item.continentDesc }}</p>
          </li>
        </ul>
      </section>
    </section>

    <van-pull-refresh class="f-list" v-model="refreshing" @refresh="onRefresh">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <My-Waterfall :productList="tableData" v-if="tableData.length"></My-Waterfall>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="popupCode" position="bottom" round class="f-popup-code" closeable>
      <p class="f-title">选择用户码</p>
      <section class="f-select">
        <p :class="{'f-select-s': selectS == 2}" @click="changeTabbarCode(2)">我的设备用户码</p>
        <p :class="{'f-select-s': selectS == 1}" @click="changeTabbarCode(1)">最近充值用户码</p>
      </section>
      <ul class="f-check-ul">
        <li v-for="(item,index) in codeList" :key="index" @click="selectCode(item)"
          :style="{'color': item == code? '#304EEE': ''}">
          <p>
            <span>{{item}}</span>
            <!-- <span style="font-size: 12px;">（FM_U8）</span> -->
          </p>
          <img v-if="item == code" src="@/assets/icons/icon_tick_selected.png" alt="">
        </li>
        <li v-if="!codeList.length">暂无数据</li>
      </ul>
    </van-popup>
  </section>
</template>

<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from './api';
import { errorDeal, getStore, setStore } from '@/utils/utils';
import MyWaterfall from '@/components/MyWaterfall.vue'

export default {
  name: 'outChinaMeal',

  components: { MyWaterfall },

  emits: ["changeMealType"],

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      code: getStore('CURRENT_CODE').code,

      defaultImg: require('@/assets/imgs/icon_country_default.png'),
      defaultMealImg: require('@/assets/imgs/pic_package_default.png'),

      continentList: [
        // { url: require('@/assets/icons/package_icon_asia.png'), name: '亚洲' },
        // { url: require('@/assets/icons/package_icon_europe.png'), name: '欧洲' },
        // { url: require('@/assets/icons/package_icon_africa.png'), name: '非洲' },
        // { url: require('@/assets/icons/package_icon_america.png'), name: '美洲' },
        // { url: require('@/assets/icons/package_icon_oceania.png'), name: '大洋洲' },
      ],
      continentImg: {
        'Asia': require('@/assets/icons/package_icon_asia.png'),
        'Europe': require('@/assets/icons/package_icon_europe.png'),
        'Africa': require('@/assets/icons/package_icon_africa.png'),
        'America': require('@/assets/icons/package_icon_america.png'),
        'Oceania': require('@/assets/icons/package_icon_oceania.png'),
      },

      searchForm: {
        "condition": '', // 1-区域，2-全球，按洲或国家查传Null
        "continentCode": "", // 洲码
        "countryCode": "", // 国家码
        "orderBy": "",
        "page": 1,
        "serverEnum": null,
        "size": 10,
        "sortOrder": "DESC",
        "trafficEnd": "",
        "trafficStart": "",
        "typeEnum": null
      },

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,

      popupCode: false,
      selectS: 2,
      codeList: [],
      recentcodeList: [],
      cardsList: [],

      isBack: route.query.mealType,
    })

    onMounted(() => {
      getYklHotLocation()
      getCards()
    })

    const getYklHotLocation = () => {
      api.yklHotLocation().then(res => {
        state.continentList = res.data.continentOptionsList
        state.searchForm.continentCode = state.continentList[0].continentCode
        onLoad()
      })
    }

    const onLoad = () => {
      if (!state.searchForm.continentCode) {
        state.refreshing = false
        state.finished = false;
        state.loading = false;
        return
      }
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      api.yklPackListMore(json).then(res => {
        state.refreshing = false

        if (res.data.list.length) state.searchForm.page += 1
        state.tableData.push(...res.data.list)

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const pageBack = () => {
      router.go(-1)
    };

    const toSearch = () => {
      router.push({
        path: '/outChinaMeal/search',
        query: {}
      })

      addCacheRoute()
    }

    const addCacheRoute = () => {
      store.commit("addCacheRoute", 'outChinaMeal');
    }

    const handleContinent = (data) => {
      state.searchForm.continentCode = data.continentCode
      state.tableData = []
      onRefresh()
    }

    // 获取最近充值的设备用户码
    const getRecentcode = () => {
      api.recentcode().then(res => {
        let recentcodeList = []
        if (res.data && res.data.length) {
          res.data.forEach(item => {
            recentcodeList.push(item.code)
          })
        }
        state.recentcodeList = recentcodeList
      })
    }

    const getCards = () => {
      api.cards().then(res => {
        let cardsList = []
        if (res.data.devList) {
          res.data.devList.forEach(item => {
            cardsList.push(item.code)
          })
        }
        state.cardsList = cardsList
        changeTabbarCode(2)
      })
    }

    const changeTabbarCode = (selectS) => {
      state.selectS = selectS
      if (selectS == 1) {
        state.codeList = state.recentcodeList
      } else {
        state.codeList = state.cardsList
      }
    }

    const setCode = () => {
      setStore('CURRENT_CODE', { code: state.code })
    }

    const selectCode = (code) => {
      state.code = code
      state.popupCode = false
      setCode()
    }

    const changeMealType = (type) => {
      context.emit('changeMealType', type)
    }

    const openPopupCode = () => {
      state.popupCode = true
      getRecentcode()
    }

    return {
      ...toRefs(state),
      pageBack,
      toSearch,
      onLoad,
      onRefresh,
      handleContinent,
      setCode,
      selectCode,
      changeTabbarCode,
      changeMealType,
      openPopupCode
    }
  }
}
</script>

<style lang='scss' scoped>
.f-meal {
  display: flex;
  flex-direction: column;
  height: 92%;
  :deep(.van-cell:after) {
    position: relative;
  }
  :deep(.van-field__control) {
    color: #fff;
  }
  .f-top-box {
    height: 370px;
  }
  .f-nav-left {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 14px;
    color: #000000;
    img {
      width: 22px;
      height: 22px;
      margin-right: 5px;
    }
  }
  .f-header {
    width: 375px;
    background: #293b63;
    font-weight: 400;
    font-size: 12px;
    color: #ffffff;
    padding: 24px 12px 24px 20px;
    .f-code {
      margin-top: 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .f-input {
        width: 250px;
        background: #293b63;
        padding-left: 0;
        font-size: 18px;
      }
      img {
        width: 7px;
      }
    }
  }
  .f-search {
    background-repeat: no-repeat;
    width: 100%;
    .f-search-box {
      width: 341px;
      height: 58px;
      background: #ffffff;
      border-radius: 17px;
      border: 1px solid #6717cd;
      margin-left: 17px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 16px;
      color: #aaaaaa;
      padding-left: 15px;
      img {
        width: 21px;
        height: 21px;
        margin-right: 12px;
      }
    }
    .f-continent-box {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-top: 17px;
      li {
        text-align: center;
        width: 44px;
        padding-bottom: 7px;
        border-bottom: 3px solid #f5f5f5;
        img {
          width: 30px;
          height: 30px;
          margin-bottom: 2px;
        }
      }
      .f-continent-active {
        border-bottom: 3px solid #000000;
      }
    }
  }
  .f-list {
    overflow-y: auto;
    flex: 1;
    background: #ffffff;
  }
  .f-popup-code {
    min-height: 400px;
    .f-title {
      font-weight: 500;
      font-size: 16px;
      color: #000000;
      text-align: center;
      padding: 14px 0 0px 0;
    }
    .f-select {
      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 12px;
      color: #424242;
      justify-content: center;
      margin: 19px 0 30px 0;
      p {
        padding: 7px 12px;
        background: #d9d9d9;
        border: 2px solid #d9d9d9;
      }
      p:first-child {
        border-radius: 3px 0 0 3px;
      }
      p:last-child {
        border-radius: 0 3px 3px 0;
      }
      .f-select-s {
        background: #ffffff;
        color: #3967d9;
      }
    }
    .f-check-ul {
      padding: 0 13px 40px 24px;
      li {
        font-weight: 400;
        font-size: 16px;
        color: #424242;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 40px;
        img {
          width: 21px;
          height: 14px;
        }
      }
    }
  }
}
</style>